namespace SimpleWebServices.Web.UI
{
    using System;
    using System.Net;
    using System.Web;
    using System.Web.UI;

    public class DefaultPage : Page
    {
        private string _location;
        private Uri _path;

        public DefaultPage()
            : this("home")
        {
        }

        public DefaultPage(string path)
        {
            if (null == path)
            {
                throw new ArgumentNullException("path");
            }
            else if (0 == path.Length)
            {
                throw new ArgumentOutOfRangeException("path");
            }

            this.Path = new Uri(path, UriKind.Relative);
        }

        public string Location
        {
            get
            {
                if (null == this._location)
                {
                    this._location = HttpContextFactory.Current.Request.Url.ToUri(this.Path).AbsoluteUri;
                }

                return this._location;
            }
        }

        public Uri Path
        {
            get
            {
                return this._path;
            }

            set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }
                else if (value.IsAbsoluteUri)
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                this._path = value;
            }
        }

        public virtual void Page_Load(object sender, EventArgs e)
        {
            var response = HttpContextFactory.Current.Response;

            response.StatusCode = (int)HttpStatusCode.SeeOther;
            response.AppendHeader("Location", this.Location);
            response.ContentType = "text/html";
            response.Cache.SetCacheability(HttpCacheability.Public);
            response.Cache.SetExpires(DateTimeFactory.UtcNow.AddDays(1));
        }
    }
}